
from ruamel.yaml import YAML
import os
from typing import Any, Dict

CONFIG_PATH = os.path.abspath("config/config.yaml")

def get_config() -> Dict[str, Any]:
    yaml = YAML()
    yaml.preserve_quotes = True
    try:
        if not os.path.exists(CONFIG_PATH):
            return {"__error__": f"配置文件未找到: {CONFIG_PATH}"}
        with open(CONFIG_PATH, "r", encoding="utf-8") as f:
            data = yaml.load(f)
            if not isinstance(data, dict):
                return {"__error__": f"配置文件内容为空或格式错误: {CONFIG_PATH}"}
            return data
    except Exception as e:
        return {"__error__": str(e)}

def save_config(config: Dict[str, Any]) -> None:
    from ruamel.yaml.comments import CommentedMap
    yaml = YAML()
    yaml.preserve_quotes = True
    yaml.indent(mapping=2, sequence=4, offset=2)
    def deep_merge(old, new):
        if not isinstance(old, dict) or not isinstance(new, dict):
            return new
        merged = CommentedMap(old)
        for k, v in new.items():
            if k in merged and isinstance(merged[k], dict) and isinstance(v, dict):
                merged[k] = deep_merge(merged[k], v)
            else:
                merged[k] = v
        return merged
    try:
        if os.path.exists(CONFIG_PATH):
            with open(CONFIG_PATH, "r", encoding="utf-8") as f:
                old_config = yaml.load(f) or CommentedMap()
        else:
            old_config = CommentedMap()
        merged_config = deep_merge(old_config, config)
        if len(merged_config.keys()) < len(old_config.keys()):
            return
        with open(CONFIG_PATH, "w", encoding="utf-8") as f:
            yaml.dump(merged_config, f)
    except Exception:
        pass
